package com.zhouchb.blog.Controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhouchb.blog.bean.*;
import com.zhouchb.blog.service.*;
import com.zhouchb.blog.util.UtilsTag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Zhouchb
 * @Create 2021-09-2021/9/4 :16:23
 * @Description
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypesService typesService;
    @Autowired
    private TagsService tagesService;
    @Autowired
    private UtilsTag utilsTag;
    @Autowired
    private BlogTagService blogTagService;
    @Autowired
    private UserService userService;

    public void setTypeAndTag(Model model) {
        List<Type> types = typesService.listType();
        List<Tag> tags = tagesService.listTagService();
        model.addAttribute("tags", tags);
        model.addAttribute("types", types);
    }

    @GetMapping("/blogs")
    public String blogs(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
       // log.info("/blogs-pn:{},", pn);
        List<Type> types = typesService.listType();
        PageHelper.startPage(pn, 6);
        List<Blog> blogs = blogService.getAllBlogDao();
        PageInfo<Blog> blogPageInfo = new PageInfo<>(blogs, 5);
        model.addAttribute("blogpageInfo", blogPageInfo);
        model.addAttribute("types", types);
        return "admin/blogs";
    }

    @PostMapping("/blogs/search")
    public String blogsSearch(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Blog blog, Model model) {
       // log.info("/search-pn:{}", pn);
        if (pn == 0) {
            pn = pn + 1;
        }
        PageHelper.startPage(pn, 6);
        List<Blog> blogs = blogService.listBlogService(blog);
        PageInfo<Blog> blogPageInfo = new PageInfo<>(blogs, 5);
        model.addAttribute("blogpageInfo", blogPageInfo);
        return "admin/blogs :: blogList"; //blogs页面下的bloglist
    }

    //新增
    @GetMapping("/release")
    public String toRelease(Model model) {
        setTypeAndTag(model);
        model.addAttribute("blog", new Blog());
        return "admin/release";
    }

    //新增/更新博客
    @PostMapping("/blogs")
    public String saveBlog(Blog blog, HttpSession session, @RequestParam("firstImg") MultipartFile firstImg, RedirectAttributes redirectAttributes) throws IOException {
        log.info("首图大小：{},title{},id{}", firstImg.getSize(), blog.getTitle(), blog.getId());
        //图片名
        String originalFilename = firstImg.getOriginalFilename();
        List<Blog> blogList = blogService.searchPictureService(blog.getFirstPicture());
        log.info("FirstPicture:{}",blog.getFirstPicture());
        if (firstImg != null && blogList.size() == 0 ) {
//                 firstImg.transferTo(new File("E:\\javadev\\imgDownload\\" + originalFilename));
                  firstImg.transferTo(new File("/usr/blogPic/" + originalFilename));
            blog.setFirstPicture("http://124.71.220.235/blogPic/" + originalFilename);
        }
        User user = (User) session.getAttribute("user");
        Long id = user.getId();
        blog.setUserId(id);
        blog.setTypeId(blog.getType().getId());
        int i = 0;
        if (blog.getId() == null) {
            blog.setViews(0);
            i = blogService.saveBlogService(blog);
        } else {
            i = blogService.updateBlogService(blog.getId(), blog);
        }
        System.out.println(blog.getTagIds().length());
        System.out.println("===" + blog.getTagIds() + "=====");
        if (blog.getTagIds().length() != 0) {
            List<Long> list = utilsTag.converToList(blog.getTagIds());
            List<BlogsTags> blogsTagsList = new ArrayList<>();
            Long blogId = blog.getId();
            for (Long aLong : list) {
                blogsTagsList.add(new BlogsTags(null, blogId, aLong));
            }
            blogTagService.delListByBlog(blogId);
           // log.info("删除了？");
            blogTagService.saveListService(blogsTagsList);
        } else {
            Long blogId = blog.getId();
            blogTagService.delListByBlog(blogId);
        }
        if (i > 0) {
            redirectAttributes.addFlashAttribute("BlogMessage", "恭喜恭喜！博客操作成功！");
        } else {
            redirectAttributes.addFlashAttribute("FailBlogMessage", "哎呀呀！添加博客操作失败了呀！");
        }
        return "redirect:/admin/blogs";
    }

    //更新/blogs/{id}/input(id=${blog.id})
    @GetMapping("/blogs/{id}/input")
    public String toUpdateRelease(@PathVariable("id") Long id, Model model) {
        setTypeAndTag(model);
        Blog blog = blogService.getBlogByIdService(id);
        List<BlogsTags> tags = blogTagService.getByBlogService(blog.getId());
        String tagIds = utilsTag.converTagIds(tags);
        blog.setTagIds(tagIds);
        Type type = typesService.getType(blog.getTypeId());
        blog.setType(type);
        model.addAttribute("blog", blog);
        System.out.println(blog);
        return "admin/release";
    }

    //删除/blogs/{id}/delete(id=${blog.id})
    @ResponseBody
    @GetMapping("/blogs/delete/{id}")
    public String delBlog(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        log.info("进到删除id:{}",id);
        blogTagService.delListByBlog(id);
        blogService.delBlogService(id);
        redirectAttributes.addFlashAttribute("BlogMessage", "博客删除成功！");
        return "redirect:/admin/blogs";
    }

}
